package fun.boomcat.luckyhe.mirai.plugin.command;

import fun.boomcat.luckyhe.mirai.plugin.config.RconCommandConfigOperation;
import fun.boomcat.luckyhe.mirai.plugin.pojo.Player;
import fun.boomcat.luckyhe.mirai.plugin.service.PlayerListService;
import fun.boomcat.luckyhe.mirai.plugin.service.PlayerListServiceImpl;
import fun.boomcat.luckyhe.mirai.plugin.utils.CommandMappingWebThread;
import fun.boomcat.luckyhe.mirai.plugin.utils.PlayerCommandHelp;
import fun.boomcat.luckyhe.mirai.plugin.utils.RconUtil;
import kotlin.Unit;
import kotlin.coroutines.Continuation;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandOwner;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.RawCommand;
import net.mamoe.mirai.console.permission.Permission;
import net.mamoe.mirai.contact.User;
import net.mamoe.mirai.message.data.MessageChain;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;

public class PlayerCommand extends RawCommand {

    public PlayerCommand(@NotNull CommandOwner owner, @NotNull String primaryName, @NotNull String[] secondaryNames, @NotNull String usage, @NotNull String description, @NotNull Permission parentPermission, boolean prefixOptional) {
        super(owner, primaryName, secondaryNames, usage, description, parentPermission, prefixOptional);
    }

    @Nullable
    @Override
    public Object onCommand(@NotNull CommandSender commandSender, @NotNull MessageChain messageChain, @NotNull Continuation<? super Unit> continuation) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        String primaryName = this.getPrimaryName();
        String[] secondaryNames = this.getSecondaryNames();

        int mcLen = messageChain.toArray().length;
        if (mcLen == 0) {
            commandSender.sendMessage(PlayerCommandHelp.helpStr(primaryName, secondaryNames));
            return null;
        }

        String operation = messageChain.get(0).toString();

        switch (operation.toLowerCase()) {
            case "setmcid":
            case "设置mcid":
                onSetMcId(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        secondaryNames
                );
                break;
            case "list":
            case "所有指令":
                onList(
                        commandSender,
                        primaryName,
                        secondaryNames
                );
                break;
            default:
                commandSender.sendMessage("有奇怪的参数，" + commandPrefix + primaryName + "查看帮助");
                break;
        }
        return null;
    }

    private void onSetMcId(CommandSender commandSender, Object[] args, String primaryName, String[] secondaryNames) {
        int argLen = args.length;
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        if (argLen != 1 && argLen != 2) {
            commandSender.sendMessage(PlayerCommandHelp.setMcIdHelpStr(primaryName));
            return;
        }

        String mcId = args[0].toString();
        User user = commandSender.getUser();
        long qq = user != null ? user.getId() : 0;
        PlayerListService service = new PlayerListServiceImpl();

        if (argLen == 1) {
            Random random = new Random();

            int confirmCode;
            do {
                confirmCode = random.nextInt(1000000);
            } while (confirmCode < 100000);

            Player player = new Player();
            player.setQq(qq);
            player.setMcId(mcId);
            player.setChecked(false);
            player.setConfirmCode(confirmCode);

            StringBuilder sb = new StringBuilder();
            sb.append("tellraw ").append(mcId).append(" ");
            sb.append("{\"text\": \"\", \"color\":\"gold\", \"extra\": [{\"text\": \"==============================\\n\", \"color\": \"red\"}, \"用于绑定qq与mcid的验证码：\", {\"text\":\"")
                    .append(confirmCode)
                    .append("\\n\", \"color\": \"green\"}, {\"text\": \"==============================\", \"color\": \"red\"}]}");

            try {
                RconUtil.sendMcCommand(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
                commandSender.sendMessage("错误：发送指令失败");
                return;
            }

            try {
                int res = service.insertOnePlayer(player);
                if (res != 1) {
                    commandSender.sendMessage("插入失败");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                commandSender.sendMessage("错误：插入玩家失败");
                return;
            }

            commandSender.sendMessage("已发送验证码到mc中（玩家要在线才能收到，如没有收到可使用同一条指令重发）\n" +
                    "使用以下指令确认绑定：\n" + commandPrefix + primaryName + " setmcid " +
                    mcId + " <验证码>");
            return;
        } else if (argLen == 2) {
            String confirmCode = args[1].toString();
            int cc;
            try {
                cc = Integer.parseInt(confirmCode);
            } catch (Exception e) {
                e.printStackTrace();
                commandSender.sendMessage("错误：验证码应该为数字");
                return;
            }

            Player player;

            try {
                player = service.selectPlayerByQq(qq);
                if (player == null) {
                    throw new Exception("数据库中没有该条记录");
                }
            } catch (IOException e) {
                e.printStackTrace();
                commandSender.sendMessage("错误：处理失败，请重试");
                return;
            } catch (Exception e) {
                e.printStackTrace();
                commandSender.sendMessage("错误：" + e.toString());
                return;
            }

            if (player.getConfirmCode() == cc) {
                player.setChecked(true);
                try {
                    service.insertOnePlayer(player);
                } catch (IOException e) {
                    e.printStackTrace();
                    commandSender.sendMessage("错误：操作失败，请重试");
                    return;
                }

                commandSender.sendMessage("绑定完成\nqq：" + player.getQq() +
                        "\nmcid：" + player.getMcId());
            } else {
                commandSender.sendMessage("验证码不正确，绑定失败\n可再次发送指令重新获取");
                return;
            }
        }
    }

    private void onList(CommandSender commandSender, String primaryName, String[] secondaryNames) {
        try {
            CommandMappingWebThread.showAllCommandMappings();
            Map<String, String> webMap = RconCommandConfigOperation.getWebsiteInfo();
            String host = webMap.get("host");
            int port = Integer.parseInt(webMap.get("port"));

            String res = "点击查看：http://" + host + ":" + port;
            commandSender.sendMessage(res);
        } catch (Exception e) {
            e.printStackTrace();
            commandSender.sendMessage("错误：处理失败，请重试");
        }
    }
}
